<template>
    <div class="poster" v-cloak>
        <div class="title">
            选择你需要的海报，并上传 <span class="red">个人微信二维码</span> <br>替换海报内空白区域
        </div>
        <div class="wrap" :style="{'height': posterheight + 'px'}">
            <mt-swipe :auto="0" @change="idx => posterIndex = idx">
                <mt-swipe-item v-for="img in imgURLs" :key="img.id"><img :src="img.url"></mt-swipe-item>
            </mt-swipe>
        </div>
        <div class="text-center">
            <div class="tip">长按图片保存至相册</div>
            <base64-upload @change="QRCodeUpload"></base64-upload>
        </div>
        <div class="submit">
            <mt-button size="large" type="primary" @click="savePoster">确定</mt-button>
        </div>
    </div>
</template>

<script>
    import MCanvas from '@/assets/mCanvas.js'
    import { uploadToOSS, getAllPost, updateCourseCode } from '@/api'
    import { getRandomCharacters } from '@/assets/util.js'
    import Base64Upload from '@/components/Base64Upload.vue'
    import { MessageBox } from 'mint-ui';
    export default {
        name: 'course-poster',
        components: {
            Base64Upload
        },
        data() {
            return {
                posterheight: 560,
                codeSize: '',
                imgURLs: [],
                uploadedCode: '',
                posterIndex: 0,
                QRCode: {},
                uploadOptions: {
                    host: 'http://penguin-courses.oss-cn-shanghai.aliyuncs.com',
                    policy: 'eyJleHBpcmF0aW9uIjoiMjAzMC0wMS0wMVQxMjowMDowMC4wMDBaIiwiY29uZGl0aW9ucyI6W1siY29udGVudC1sZW5ndGgtcmFuZ2UiLDAsMTA0ODU3NjAwMF1dfQ==',
                    OSSAccessKeyId: 'LTAIAA5oGypvXDOP',
                    signature: 'jbFuR5tNtsQqfN0bVWGK17KQ7Ac=',
                }
            }
        },
        mounted() {
            this.posterheight = (window.innerWidth - 180) * 1334 / 750
            this.getAllPost()
        },
        methods: {
            getAllPost(){
                getAllPost().then(res => {
                    this.imgURLs = res.data.result
                    let headUrl = window.sessionStorage.getItem('headUrl')
                    if(headUrl){
                        this.uploadedCode = headUrl
                        let img = window.document.createElement('a')
                        img.href=headUrl
                        let name = img.pathname.split('/')[2].split('.')[0]
                        let ext = img.pathname.split('/')[2].split('.')[1]
                        this.QRCode.name = name.substring(0,10)+'.'+ext
                        let ops = {
                            "image": headUrl + '?d=' + new Date().getTime(),
                            // "image": 'http://penguin-courses.oss-cn-shanghai.aliyuncs.com/image/admin-code.jpg',
                            "options": { "width": 135, "height": 135, "pos": { "x": 475/750*100+'%', "y": 1153/1334*100+'%', "scale": 1, "rotate": 1 } }
                        }
                        for (let i in this.imgURLs) {
                            this.mcDraw(ops, i)
                        }
                    }
                })
            },
            QRCodeUpload(img) {
                let _t = this
                _t.QRCode = img
                console.log(img)
                let b64 = 'data:image/jpeg;base64,' + img.base64
                let { host } = _t.uploadOptions
                let key = _t.getFileKey(img.name)
                let OssData = _t.initOssData(key, b64)
                uploadToOSS(host, OssData).then(() => {
                    updateCourseCode({headUrl: host + '/image/' + key}).then( () => {
                        this.uploadedCode = host + '/image/' + key
                        this.$toast({
                            message: '上传成功',
                            position: 'top',
                            duration: 1000
                        })
                    })
                })

                let ops = {
                    "image": b64,
                    // "image": 'http://penguin-courses.oss-cn-shanghai.aliyuncs.com/image/admin-code.jpg',
                    "options": { "width": 135, "height": 135, "pos": { "x": 475/750*100+'%', "y": 1153/1334*100+'%', "scale": 1, "rotate": 1 } }
                }
                for (let i in this.imgURLs) {
                    this.mcDraw(ops, i)
                }
            },
            mcDraw(ops, index) {
                let _t = this
                const mc = new MCanvas();
                mc.background(_t.imgURLs[index].url, {
                    type: 'origin'
                });
                let img = new Image();
                img.crossOrigin = 'anonymous';
                img.onload = function() {
                    mc.add(img, ops.options).draw({
                        type: 'jpg',
                        quality: .8,
                        success: function success(b64) {
                            console.log('success')
                            let id=_t.imgURLs[index].id
                            let name=_t.imgURLs[index].name
                            _t.imgURLs.splice(index, 1, {url:b64, id, name})
                        },
                        error: function error(err) {
                            alert(err);
                        }
                    });
                };
                img.src = ops.image;
            },
            savePoster() {
                let _t = this
                if (!_t.uploadedCode) {
                    MessageBox('提示', '请上传群主微信二维码');
                    return false;
                }
                _t.$indicator.open({
                    text: '上传中...',
                    spinnerType: 'fading-circle'
                });
                let b64 = _t.imgURLs[_t.posterIndex].url
                let { host } = _t.uploadOptions
                let key = _t.getFileKey(_t.QRCode.name)
                let OssData = _t.initOssData(key, b64)
                uploadToOSS(host, OssData).then(res => {
                    // _t.imgURLs.splice(_t.posterIndex, 1, host + '/image/' + key)
                    _t.$indicator.close()
                    window.sessionStorage.setItem('posterInfo',JSON.stringify({
                        id: _t.imgURLs[_t.posterIndex].id,
                        name: _t.imgURLs[_t.posterIndex].name,
                        url: host + '/image/' + key,
                        headUrl: _t.uploadedCode
                    }))
                    _t.$router.push('config')
                })

            },
            getFileKey(fullName){
                let nameArg = fullName.split('.'),
                    fileName = nameArg[0],
                    fileExt = nameArg.length > 1 ? ('.' + nameArg[nameArg.length - 1]) : '',
                    key = fileName + '____' + getRandomCharacters(8) + fileExt;
                return key
            },
            initOssData(key, b64){
                let fileBlob = this.dataURLToBlob(b64)
                let OssData = new FormData()
                let { policy, OSSAccessKeyId, signature } = this.uploadOptions
                OssData.append('key', 'image/' + key)
                OssData.append('policy', policy)
                OssData.append('OSSAccessKeyId', OSSAccessKeyId)
                OssData.append('signature', signature)
                OssData.append('success_action_status', 200)
                OssData.append('Filename', key)
                OssData.append('file', fileBlob)
                
                return OssData
            },
            dataURLToBlob(dataurl) {
                var arr = dataurl.split(','),
                    mime = arr[0].match(/:(.*?);/)[1],
                    bstr = atob(arr[1]),
                    n = bstr.length,
                    u8arr = new Uint8Array(n);
                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n);
                }
                return new Blob([u8arr], { type: mime });
            },
            dataURLtoFile(dataurl, filename) {
                var arr = dataurl.split(','),
                    mime = arr[0].match(/:(.*?);/)[1],
                    bstr = atob(arr[1]),
                    n = bstr.length,
                    u8arr = new Uint8Array(n);
                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n);
                }
                return new File([u8arr], filename, { type: mime });
            }
        }
    }
</script>

<style scoped lang="scss">
    .poster{
        position: fixed;
        top: 0;
        bottom: 0;
        width: 100%;
        padding-bottom: .6rem;
        overflow-y: auto;
    }
    .poster /deep/ {
        .title {
            padding: .1rem;
            text-align: center;
            line-height: 1.6;

            .red {
                color: #D0021B;
            }
        }

        .wrap {
            padding: 0 90px 10px;
            img {
                width: 100%;
            }
        }

        .tip {
            color: var(--tipColor);
            font-size: 13px;
            padding-bottom: 10px;
        }

        .submit {
            position: fixed;
            bottom: 0;
            width: 100%;
            .mint-button--large {
                border-radius: 0;
            }
        }
    }

    img.test {
        width: 100%;
    }
</style>